package org.bread.worm.cms.web.controller;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.bread.worm.cms.auth.AuthClass;
import org.bread.worm.cms.auth.AuthMethod;
import org.bread.worm.cms.basic.bean.Pager;
import org.bread.worm.cms.channel.bean.ChannelTree;
import org.bread.worm.cms.channel.service.ChannelService;
import org.bread.worm.cms.user.bean.Role;
import org.bread.worm.cms.user.bean.RoleType;
import org.bread.worm.cms.user.bean.User;
import org.bread.worm.cms.user.bean.UserDto;
import org.bread.worm.cms.user.service.GroupService;
import org.bread.worm.cms.user.service.RoleService;
import org.bread.worm.cms.user.service.UserService;
import org.jboss.logging.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@AuthClass("login")
@RequestMapping("/admin/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private GroupService groupService;

	@Autowired
	private ChannelService channelService;

	@GetMapping("list")
	public String list(Model model) {
		Pager<User> datas = userService.findUser();
		model.addAttribute("datas", datas);
		return "user/list";
	}

	/**
	 * 导航至添加页
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("add")
	public String add(Model model) {
		UserDto userDto = new UserDto();
		model.addAttribute(userDto);
		model.addAttribute("roles", roleService.listRole());
		model.addAttribute("groups", groupService.listGroup());
		return "user/add";
	}

	/***
	 * 用户名唯一性验证
	 * 
	 * @param username
	 * @return
	 */
	@GetMapping("/valid_username")
	public @ResponseBody String valid_username(String username) {
		return String.valueOf(userService.existsByUsername(username));
	}

	/**
	 * 添加
	 * 
	 * @param userDto
	 * @param bindingResult
	 * @param model
	 * @return
	 */
	@PostMapping("add")
	public String save(@Valid UserDto userDto, BindingResult bindingResult, Model model) {
		if (bindingResult.hasErrors()) {
			model.addAttribute("roles", roleService.listRole());
			model.addAttribute("groups", groupService.listGroup());
			return "redirect:user/add";
		}
		userService.add(userDto.getUser(), userDto.getRoleIds(), userDto.getGroupIds());
		return "redirect:/admin/user/list";
	}

	@GetMapping("delete/{id}")
	public String delete(@PathVariable int id) {
		userService.delete(id);
		return "redirect:/admin/user/list";

	}

	@GetMapping("updateStatus/{id}")
	public String updateStatus(@PathVariable int id) {
		userService.updateStatus(id);
		return "redirect:/admin/user/list";
	}

	@GetMapping("update/{id}")
	public String update(@PathVariable int id, Model model) {
		User user = userService.load(id);
		model.addAttribute("roles", roleService.listRole());
		model.addAttribute("groups", groupService.listGroup());
		model.addAttribute("userDto",
				new UserDto(user, userService.listUserRoleIds(id), userService.listUserGroupIds(id)));
		return "user/update";
	}

	@PostMapping("update/{id}")
	public String update(@PathVariable int id, @Valid UserDto userDto, BindingResult bindingResult, Model model) {
		User user = userService.load(id);
		if (bindingResult.hasErrors()) {
			model.addAttribute("roles", roleService.listRole());
			model.addAttribute("groups", groupService.listGroup());
			return "user/update";
		}
		user.setNickname(userDto.getNickname());
		user.setEmail(userDto.getEmail());
		user.setStatus(userDto.getStatus());
		user.setPhone(userDto.getPhone());
		userService.update(user, userDto.getRoleIds(), userDto.getGroupIds());
		return "redirect:/admin/user/list";
	}

	@GetMapping("{id}")
	public String show(@PathVariable int id, Model model) {
		User user = userService.load(id);
		model.addAttribute("user", user);
		model.addAttribute("roles", userService.listUserRoles(id));
		model.addAttribute("groups", userService.listUserGroups(id));
		return "user/show";
	}

	@PostMapping("/userTree/{uid}")
	public @ResponseBody List<ChannelTree> userTree(@PathVariable Integer uid) {
		return groupService.generateUserChannelTree(uid);
	}

	@GetMapping("/listChannels/{uid}")
	public String listChannels(@PathVariable int uid, Model model) {
		model.addAttribute(userService.load(uid));
		List<Role> rs = userService.listUserRoles(uid);
		for (Role r : rs) {
			if (r.getRoleType() == RoleType.ROLE_ADMIN) {
				model.addAttribute("isAdmin", 1);
			}
		}
		return "/user/listChannel";
	}

	@GetMapping("/userTree/{uid}")
	public @ResponseBody List<ChannelTree> groupTree(@PathVariable Integer uid, @Param Integer isAdmin) {
		if (isAdmin != null && isAdmin == 1) {
			return channelService.generateTree();
		}
		return groupService.generateUserChannelTree(uid);
	}

	@GetMapping("/showSelf")
	@AuthMethod
	public String showSelf(Model model, HttpSession session) {
		User user = (User) session.getAttribute("loginUser");
		model.addAttribute(user);
		model.addAttribute("gs", userService.listUserGroups(user.getId()));
		model.addAttribute("rs", userService.listUserRoles(user.getId()));
		return "user/show";
	}

	@GetMapping(value = "/updatePwd")
	@AuthMethod
	public String updatePwd(Model model, HttpSession session) {
		User u = (User) session.getAttribute("loginUser");
		model.addAttribute(u);
		return "user/updatePwd";
	}

	@PostMapping(value = "/updatePwd")
	@AuthMethod
	public String updatePwd(int id, String oldPwd, String password) {
		userService.updatePwd(id, oldPwd, password);
		return "redirect:/admin/user/showSelf";
	}

	/*
	 * @RequestMapping(value="/updatePwd",method=RequestMethod.POST) public
	 * String updatePwd(Model model,HttpSession session) { User u =
	 * (User)session.getAttribute("loginUser"); model.addAttribute(u); return
	 * "user/updatePwd"; }
	 */

	@GetMapping(value = "/updateSelf")
	@AuthMethod
	public String updateSelf(Model model, HttpSession session) {
		User u = (User) session.getAttribute("loginUser");
		model.addAttribute(new UserDto(u));
		return "user/updateSelf";
	}

	@PostMapping(value = "/updateSelf")
	@AuthMethod
	public String updateSelf(@Valid UserDto userDto, BindingResult br, Model model, HttpSession session) {
		if (br.hasErrors()) {
			return "user/updateSelf";
		}
		User ou = userService.load(userDto.getId());
		ou.setNickname(userDto.getNickname());
		ou.setPhone(userDto.getPhone());
		ou.setEmail(userDto.getEmail());
		userService.update(ou);
		session.setAttribute("loginUser", ou);
		return "redirect:/admin/user/showSelf";
	}

}
